var fs = require("fs");
var path = require("path");
const nodeXlsx = require("node-xlsx");

/**
 * 初始化参数
 */
const oldColumnIndex = process.argv[2];
const newColumnIndex = process.argv[3];

function runUpdate() {
  // 读取execl
  const urlsPath = path.resolve("./urls.xlsx");
  const urlMap = getUrlsData(urlsPath);
  console.log(urlMap);

  const pagesPath = path.resolve("../../pages");
  const constPath = path.resolve("../../const");
  const componentsPath = path.resolve("../../components");
  transContent(pagesPath, urlMap);
  transContent(constPath, urlMap);
  transContent(componentsPath, urlMap);
}

runUpdate()

/**
 * 获取url值
 * @param {*} path
 * @returns
 */
function getUrlsData(path) {
  const result = {
    oldList: [],
    newList: [],
  };
  const sheets = nodeXlsx.parse(path);
  sheets.forEach((sheet) => {
    // sheet.data是所有行数据
    let rows = sheet.data;
    rows.forEach((row, index) => {
      if (index !== 0) {
        result.oldList.push(row[oldColumnIndex]);
        result.newList.push(row[newColumnIndex]);
      }
    });
  });
  return result;
}

/**
 * 文件遍历替换内容
 * @param {*} filePath
 */
async function transContent(filePath, urlMap) {
  try {
    //根据文件路径读取文件，返回文件列表
    const files = await fs.readdirSync(filePath);
    //遍历读取到的文件列表
    files.forEach(function (filename) {
      //获取当前文件的绝对路径
      var filedir = path.join(filePath, filename);
      //根据文件路径获取文件信息，返回一个fs.Stats对象
      const stats = fs.statSync(filedir);
      var isFile = stats.isFile(); //是文件
      var isDir = stats.isDirectory(); //是文件夹
      if (isFile) {
        let content = fs.readFileSync(filedir, "utf8");
        let isTrans = false;
        urlMap.oldList.forEach((item, index) => {
          const reg = new RegExp(item, "g");
          if (content.match(reg)) {
            isTrans = true;
            content = content.replace(reg, urlMap.newList[index]);
          }
        });

        if (isTrans) {
          fs.writeFile(filedir, content, "utf8", (error) => {
            if (error) throw error;
            console.log("替换成功：", filedir);
          });
        }
      }
      if (isDir) {
        transContent(filedir, urlMap); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
      }
    });
  } catch (error) {
    console.log(error);
  }
}
